package ntu.edu.cn.action;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Base64;

/**
 * Created by Administrator on 2017/1/17.
 */
public class UserAction extends BaseAction {

    private static Logger logger = Logger.getLogger(ScoreAction.class);

    /**
     * this method is aim to check the user information
     *
     * @throws Exception
     */


    public void get3rdSession() throws Exception {
        String code = getRequest().getParameter("code");
        String encryptedData = getRequest().getParameter("encryptedData");
        String iv = getRequest().getParameter("iv");
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx0b5d762cdbe953ab&secret=33a9f0fa5ed13cc51176516f0f8eccc6&js_code=" + code + "&grant_type=authorization_code";
        HttpGet httpPost = new HttpGet(url);
        try (CloseableHttpClient httpClient = getClosableHttpClient()) {
            HttpResponse re = httpClient.execute(httpPost);
            String content = EntityUtils.toString(re.getEntity());
            System.out.print(content);
            JSONObject resultJson = JSONObject.fromObject(content);
            String session_key = resultJson.getString("session_key");
            String openid = resultJson.getString("openid");
            Base64.Decoder base64 = Base64.getDecoder();
            byte[]  b=     decrypt(base64.decode(encryptedData),base64.decode(session_key),base64.decode(iv));
            String  s = new String(b);
            System.out.println(s);
            getWriter().write(resultJson.toString());
        } catch (Exception e) {
            logger.error("something is error to get data ",e);
            getWriter().print("error");
        }
    }

    public static  byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        //initialize();
        try {
            Security.addProvider(new BouncyCastleProvider());
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec,new IvParameterSpec(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
        }
        return null;
    }

}
